package org.itolik.mppextractor;
//import javax.annotation.Resource;

import net.sf.mpxj.MPXJException;
import net.sf.mpxj.ProjectFile;
import net.sf.mpxj.ResourceAssignment;
import net.sf.mpxj.mpp.MPPReader;
//import org.itolik.mppextractor.*;

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.util.*;
import java.text.*;



public class MppExtractor {

	public MppExtractor() {
		// TODO Auto-generated constructor stub
	}
	
	/**
	 * @param args
	 * @throws MPXJException 
	 */
	public static void main(String[] args) throws MPXJException {
		String ServerAaddress = "134.44.99.107";
		String DBname = "mppdb";
		String user = "mppdb";
		String password = "P@ssw0rd";
		Connection conn = null;
		Statement stmt = null; // Create statement for our quary.
		ResultSet rs = null; 	// Result variable.	
		
				//Open file. 
				MPPReader reader = new MPPReader();
				ProjectFile project = reader.read("Project1.mpp");
				
		try {
		    conn =
		       DriverManager.getConnection("jdbc:mysql://"+ ServerAaddress +"/"+DBname +
		                                   "?user="+user+"&password="+password);
		    
		    //check connection status.
		    if (conn != null) {
				System.out.println("You made it, take control your database now!");
				
				
				try {
					//Create MSQL quary connectiom.
					stmt = conn.createStatement();
					PreparedStatement InsertPrepared;
					int i = 1;
					
					stmt.executeUpdate("DELETE  FROM `Tasks`;"); //Delete all data fromDB.
				
					for (ResourceAssignment assignment : project.getAllResourceAssignments())
					{
						net.sf.mpxj.Task task = assignment.getTask();
					   String taskName;
					   if (task == null)
					   {
					      taskName = "(null task)";
					   }
					   else
					   {
					      taskName = task.getName();
					   }

					   net.sf.mpxj.Resource resource = assignment.getResource();
					   String resourceName;
					   if (resource == null)
					   {
					      resourceName = "(null resource)";
					   }
					   else
					   {
					      resourceName = resource.getName();
					   }
					   	
					  
					   //Worked variant
						 InsertPrepared = conn.prepareStatement(
								 "INSERT into " +
									   		"Tasks (Taskid, TaskName, TaskStartDate, TaskFinishDate, TaskDuration, TaskNote,TaskResource )" +
									   		" 		VALUES(?,?,?,?,?,?,?);"
						 );
						//Create Dateformat for database.
						 String[] StartDateArr =	 task.getStart().toString().split(" ");
						 String[] DurationArr =	 task.getDuration().toString().split("\\.");
						 
						 //Prepared statment for Databese
						 InsertPrepared.setInt(1, task.getID());
						 InsertPrepared.setString (2, taskName);						 
						 InsertPrepared.setString (3, StartDateArr[0]+StartDateArr[1]+StartDateArr[2]+StartDateArr[5]);
						 InsertPrepared.setString (4, task.getFinish().toString());
						 InsertPrepared.setString (5, DurationArr[0]);
						 InsertPrepared.setString (6, task.getNotes());
						 InsertPrepared.setString (7, resourceName);
						 InsertPrepared.executeUpdate();
						 
						 
				
					   
					
					
				   					 
					   System.out.println(" Resource=" + resourceName+
					//		  "Task:  " + taskName+
					//		  "\nTaskID:  " + task.getID() +
					//		  "\nUnbicID:  " + task.getUniqueID() +
					//		  "Notes: "+ task.getNotes()+
					//		  "\nDuration: " + task.getDuration()+
							  DurationArr[0]+
							"\nStart date: " + task.getStart()+
							StartDateArr[0]+StartDateArr[1]+StartDateArr[2]+StartDateArr[5]+
							
					////		"\nEnd date: " + task.getFinish()+
							"\n-------------------------"
				
								
							   );
					   i= i+1;
					   if (i==5)
					   	{break;}
					   else
					   	{continue;}
					}
					
			  
				}
				catch (SQLException ex){
				    // handle any errors
				    System.out.println("SQLException: " + ex.getMessage());
				    System.out.println("SQLState: " + ex.getSQLState());
				    System.out.println("VendorError: " + ex.getErrorCode());
				}
				finally {
				    // it is a good idea to release
				    // resources in a finally{} block
				    // in reverse-order of their creation
				    // if they are no-longer needed

				    if (rs != null) {
				        try {
				            rs.close();
				        } catch (SQLException sqlEx) { } // ignore

				        rs = null;
				    }

				    if (stmt != null) {
				        try {
				            stmt.close();
				        } catch (SQLException sqlEx) { } // ignore

				        stmt = null;
				    }
				}
			} else {
				System.out.println("Failed to make connection!");
			}
		    
		   //Catch error for connection
		} catch (SQLException ex) {
		    // handle any errors
		    System.out.println("SQLException: " + ex.getMessage());
		    System.out.println("SQLState: " + ex.getSQLState());
		    System.out.println("VendorError: " + ex.getErrorCode());
		}
		
	}



	

	

}
